<?php
declare(strict_types=1);


namespace App\Controller;


define("TOKEN", "whetong");

class Wechat
{
    public function index()
    {

        $this->valid();
    }


    //验证消息
    public function valid()
    {
        if (isset($_GET['echostr'])) {
            $echoStr = $_GET["echostr"];
            if($this->checkSignature()){
                echo $echoStr;
                exit;
            }
        } else {
            $this->responseMsg();
        }


    }

    //检查签名
    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if($tmpStr == $signature){
            return true;
        }else{
            return false;
        }
    }

    private function responseMsg()
    {
        $postArr = file_get_contents("php://input");
        $postObj = simplexml_load_string($postArr, 'SimpleXMLElement', LIBXML_NOCDATA);
        $postObj=json_decode(json_encode($postObj),true);
        $msgType = $postObj['MsgType'];

        switch ($msgType) {
            case 'event':
                $openid = $postObj['FromUserName'];
                $eventKey = $postObj['EventKey'];
                $eventKey = str_replace("qrscene_", "", $eventKey);
                $from = $postObj['ToUserName'];
                $this->qrCodeLogin($openid,$eventKey,$from);
                break;
            case 'text':
//                file_put_contents('a.txt',json_encode(['a3'=>$postObj['FromUserName']]));
                break;
            default:
                // code...
                break;
        }
        // file_put_contents('a.txt',json_encode(['user'=>$postObj->ToUserName,'token'=>$postObj->EventKey]));
        return response()->json(['code'=>0,'msg'=>'success']);
    }

    private function qrCodeLogin($openid,$token,$from)
    {

        $model = new Member();
        $user = $model->where('openid',$openid)->first();
        if($user){
            if($user->status == Err::MEMBER_STATUS_ERROR){
                return response()->json(['code' => 1002, 'msg' => '当前用户已被禁用']);
            }
           $info =  $model->where('openid',$openid)->first();
           $info->batoken=$token;
           $info->lastloginip= HomeTool::get_real_ip();
           $info->lastlogintime = time();
           $info->save();
        } else {
            $data = [
                'status' => 'enable',
                'nickname' => '微信用户'.time(),
                'openid' => $openid,
                'batoken' => $token,
                'Login_type' => 1
            ];
           $info = Member::create($data);
        }
        $msg_tpl = '<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content></xml>';
        $result =  sprintf($msg_tpl,$openid, $from, time(), '登陆成功!');
        echo $result;
    }
}
